<template>
  <div class="reference-table-container">
    <!-- 工具栏 -->
    <div class="table-toolbar">
      <div class="toolbar-left">
        <el-button link @click="handleImport">
          <el-icon><Download /></el-icon>
          导入
        </el-button>
        <el-button link @click="handleAssociate">
          <el-icon><Link /></el-icon>
          关联
        </el-button>
      </div>
    </div>

    <!-- 表格 -->
    <CLTable
      :fields="referenceFields"
      :initial-data="tableData"
      :line-height="'medium'"
      :table-config="tableConfig"
      :more-actions="moreActions"
      @node-selected="handleNodeSelected"
      @on-more-action="handleMoreAction"
    />

    <!-- 上传对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传文件"
      width="500px"
      :before-close="handleUploadDialogClose"
    >
      <el-form :model="uploadForm" label-width="80px">
        <el-form-item label="选择文件">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :on-change="handleFileChange"
            :before-upload="beforeUpload"
            :limit="1"
            accept="*/*"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持所有格式文件，单个文件不超过100MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="文件描述">
          <el-input
            v-model="uploadForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入文件描述（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleConfirmUpload"
            :loading="uploading"
          >
            确定上传
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from "vue";
  import { ElMessage, ElMessageBox } from "element-plus";
  import { Download, Link } from "@element-plus/icons-vue";
  import { uploadReferenceFile, getReferenceFileList } from "@/api/reference";
  import type { ReferenceFile } from "@/api/reference";
  import CLTable from "@/components/CLTable/index.vue";
  import type { DynamicField } from "@/components/CLTable/interface";
  import type { ProjectSearchRequest } from "@/interface/project";

  // Props
  interface Props {
    // 可以添加一些配置属性
    autoLoad?: boolean;
    showUpload?: boolean;
  }

  const props = withDefaults(defineProps<Props>(), {
    autoLoad: true,
    showUpload: true,
  });

  // Emits
  const emit = defineEmits<{
    "file-selected": [files: ReferenceFile[]];
    "file-uploaded": [file: ReferenceFile];
    "file-deleted": [file: ReferenceFile];
  }>();

  // 响应式数据
  const loading = ref(false);
  const tableData = ref<any[]>([]);
  const selectedFiles = ref<ReferenceFile[]>([]);

  // CLTable 字段配置
  const referenceFields = ref<DynamicField[]>([
    {
      id: 1,
      name: "名称",
      field: "name",
      type: "text",
      invisible: true,
      checked: true,
      disable: false,
    },
    {
      id: 2,
      name: "数据源",
      field: "dataSource",
      type: "text",
      invisible: true,
      checked: true,
      disable: false,
    },
    {
      id: 3,
      name: "描述",
      field: "description",
      type: "text",
      invisible: true,
      checked: true,
      disable: false,
    },
    {
      id: 4,
      name: "操作",
      field: "actions",
      type: "actions",
      invisible: true,
      checked: true,
      disable: false,
    },
  ]);

  // CLTable 配置
  const tableConfig = ref({
    tableH: "400px",
    page: {
      showOperationsColumn: true,
      enable: true,
      pageSizes: [10, 20, 50, 100],
      size: "default",
      disabled: false,
      background: true,
      layout: "total, sizes, prev, pager, next, jumper",
    },
    borderMode: "none", // 表格边框模式，none为无边框
  });

  // 更多操作配置
  const moreActions = ref([
    { key: "edit", label: "编辑" },
    { key: "preview", label: "预览" },
    { key: "delete", label: "删除" },
  ]);

  // 上传相关
  const uploadDialogVisible = ref(false);
  const uploading = ref(false);
  const uploadRef = ref();
  const uploadForm = reactive({
    file: null as File | null,
    description: "",
  });

  // 计算属性
  const queryParams = reactive<ProjectSearchRequest>({
    pageNo: 1,
    pageSize: 20,
    total: 0,
  });

  // 方法
  const loadData = async () => {
    try {
      loading.value = true;

      // 使用假数据，不调用 API
      console.log("使用假数据:", tableData.value);
      // queryParams.total = tableData.value.length;

      // 如果需要调用真实 API，取消下面的注释
      const { result, total: t } = await getReferenceFileList(queryParams);
      console.log("API 返回数据:", result);
      if (result && Array.isArray(result)) {
        tableData.value = result;
        // tableData.value = result.map((item: any, index: number) => ({
        //   id: item.id || item.fileId || `file-${index}`,
        //   no: (index + 1).toString(),
        //   name: item.fileName || item.name || "未知文件",
        //   fileName: item.fileName || item.name || "未知文件",
        //   dataSource: "本地上传",
        //   description: item.description || "这是对该资料的描述信息这是...",
        //   fileType: item.fileType || "unknown",
        //   fileSize: item.fileSize || 0,
        //   uploader: item.uploader || item.creatorName || "系统管理员",
        //   uploadTime: item.uploadTime || item.createTime || new Date().toISOString(),
        //   downloadUrl: item.downloadUrl || "",
        //   previewUrl: item.previewUrl || "",
        // }));
      } else {
        tableData.value = [];
      }
      queryParams.total = t || 0;
    } catch (error) {
      console.error("加载参考资料列表失败:", error);
      ElMessage.error("加载数据失败");
    } finally {
      loading.value = false;
    }
  };

  const handleNodeSelected = (nodes: any[]) => {
    selectedFiles.value = nodes;
    emit("file-selected", nodes);
  };

  const handleMoreAction = (actionKey: string, node: any) => {
    console.log("更多操作:", actionKey, node);
    // 根据 actionKey 执行不同的操作
    switch (actionKey) {
      case "edit":
        handleEdit(node);
        break;
      case "preview":
        handlePreview(node);
        break;
      case "delete":
        handleDelete(node);
        break;
    }
  };

  const handleImport = () => {
    console.log("导入文件");
    ElMessage.info("导入功能开发中...");
    // TODO: 实现导入功能
  };

  const handleAssociate = () => {
    console.log("关联文件");
    ElMessage.info("关联功能开发中...");
    // TODO: 实现关联功能
  };

  const handleEdit = (node: any) => {
    console.log("编辑文件:", node);
    ElMessage.info("编辑功能开发中...");
    // TODO: 实现编辑功能
  };

  const handlePreview = (node: any) => {
    console.log("预览文件:", node);
    if (node.previewUrl) {
      window.open(node.previewUrl, "_blank");
    } else {
      ElMessage.info("该文件暂不支持预览");
    }
  };

  const handleDelete = async (node: any) => {
    try {
      await ElMessageBox.confirm(
        `确定要删除文件 "${node.fileName}" 吗？`,
        "确认删除",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        },
      );

      // TODO: 调用删除 API
      // await deleteReferenceFile(node.id)
      ElMessage.success("删除成功");
      loadData();
      emit("file-deleted", node);
    } catch (error) {
      if (error !== "cancel") {
        console.error("删除失败:", error);
        ElMessage.error("删除失败");
      }
    }
  };

  // const handleUpload = () => {
  //   uploadDialogVisible.value = true
  // }

  const handleFileChange = (file: any) => {
    uploadForm.file = file.raw;
  };

  const beforeUpload = (file: File) => {
    const isValidSize = file.size / 1024 / 1024 < 100; // 100MB
    if (!isValidSize) {
      ElMessage.error("文件大小不能超过100MB");
      return false;
    }
    return true;
  };

  const handleConfirmUpload = async () => {
    if (!uploadForm.file) {
      ElMessage.warning("请选择要上传的文件");
      return;
    }

    try {
      uploading.value = true;
      const uploadedFile = await uploadReferenceFile(
        uploadForm.file,
        uploadForm.description,
      );
      ElMessage.success("文件上传成功");
      uploadDialogVisible.value = false;
      resetUploadForm();
      loadData();
      emit("file-uploaded", uploadedFile);
    } catch (error) {
      console.error("文件上传失败:", error);
      ElMessage.error("文件上传失败");
    } finally {
      uploading.value = false;
    }
  };

  const handleUploadDialogClose = () => {
    resetUploadForm();
    uploadDialogVisible.value = false;
  };

  const resetUploadForm = () => {
    uploadForm.file = null;
    uploadForm.description = "";
    uploadRef.value?.clearFiles();
  };

  // 工具方法

  const formatFileSize = (size: number) => {
    if (size < 1024) return size + " B";
    if (size < 1024 * 1024) return (size / 1024).toFixed(1) + " KB";
    if (size < 1024 * 1024 * 1024)
      return (size / (1024 * 1024)).toFixed(1) + " MB";
    return (size / (1024 * 1024 * 1024)).toFixed(1) + " GB";
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleString("zh-CN");
  };

  // 生命周期
  onMounted(() => {
    if (props.autoLoad) {
      loadData();
    }
  });

  // 暴露方法给父组件
  defineExpose({
    loadData,
    refresh: loadData,
  });
</script>

<style scoped lang="scss">
  .reference-table-container {
    padding: 16px;
    background: #fff;
    border-radius: 8px;
  }

  .table-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 6px;
    // padding: 16px 0;
    // border-bottom: 1px solid #e5e5e5;

    .toolbar-left {
      display: flex;
      align-items: center;
      // gap: 12px;
    }

    .toolbar-right {
      display: flex;
      align-items: center;
      gap: 12px;
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
  }

  :deep(.el-upload__tip) {
    color: #999;
    font-size: 12px;
    margin-top: 4px;
  }

  // 优化按钮样式
  :deep(.el-button) {
    border-radius: 4px;
    font-weight: 500;
  }

  :deep(.el-button--primary) {
    background-color: #409eff;
    border-color: #409eff;
  }

  // 优化输入框样式
  :deep(.el-input__wrapper) {
    border-radius: 4px;
  }

  // 优化选择器样式
  :deep(.el-select) {
    .el-input__wrapper {
      border-radius: 4px;
    }
  }
</style>
